<script setup lang="ts">
import { vOnClickOutside } from '~/directive/vOnClickOutside'

interface IProps {
  options: { label: string, value: string }[]
}

const props = defineProps<IProps>()

const open = ref(false)

const dropDownRef = ref<HTMLElement>()

const dropDownInnerRef = ref<HTMLElement>()

const options = computed(() => props.options)

const modelValue = defineModel<string[]>()!

const toggleOpen = useToggle(open)

function handleChecked({ label, checked }: { label: string, checked: boolean }) {
  if (checked && !modelValue.value!.includes(label))
    modelValue?.value?.push(label)
  if (!checked)
    modelValue.value = modelValue.value!.filter(item => item !== label)
}

watch(open, (val) => {
  if (val) {
    dropDownRef.value!.style.height = 'auto'
    const { height } = dropDownRef.value!.getBoundingClientRect()
    dropDownRef.value!.style.height = '0px'
    requestAnimationFrame(() => {
      dropDownRef.value!.style.height = `${height}px`
    })
  }
  else {
    dropDownRef.value!.style.height = '0px'
  }
})

function dropdownHandler() {
  open.value = false
}
</script>

<template>
  <div flex flex-col gap-1>
    <div relative flex flex-col cursor-pointer items-center justify-center border @click.stop="toggleOpen()">
      筛选项
    </div>
    <div ref="dropDownRef" h-0 overflow-hidden transition-all>
      <div ref="dropDownInnerRef" v-on-click-outside.bubble="dropdownHandler" border>
        <CheckBox v-for="{ label, value } of options" :key="value" :checked="modelValue?.includes(value) || false" :label="label" @update:checked="handleChecked" />
      </div>
    </div>
  </div>
</template>
